#include <iostream>
#include <string>
#include <signal.h>
#include "../comm/httplib.h"
#include "oj_model.hpp"
#include "oj_view.hpp"
#include "oj_control.hpp"

using namespace httplib;
using namespace ns_model;
using namespace ns_control;
using namespace ns_view;

static Control *ctrl_ptr = nullptr;

void Recovery(int signo)
{
    ctrl_ptr->Recovery();
}

int main()
{
    signal(SIGQUIT, Recovery);
    // 用户请求的服务路由功能
    Server svr;
    Control ctrl;
    ctrl_ptr = &ctrl;
    // 获取所有题目列表信息 
    svr.Get("/all_questions", [&ctrl](const Request &req, Response &resp){
        std::string html;
        ctrl.AllQuestions(&html);
        resp.set_content(html, "text/html;charset=utf-8");
    });

    // 用户要根据题目编号，获取题目的内容
    // 正则表达：/questions/100  ->  /questions/(\d+)
    svr.Get(R"(/questions/(\d+))", [&ctrl](const Request &req, Response &resp){
        std::string number = req.matches[1];
        std::string html;
        ctrl.OneQuestions(number, &html);
        resp.set_content(html, "text/html;charset=utf-8");
    });

    // 用户提交代码，使用我们的判题功能(1.每道题的测试用例 2.compile_and run)
    svr.Post(R"(/judge/(\d+))", [&ctrl](const Request &req, Response &resp){
        std::string number = req.matches[1];
        std::string json_result;
        ctrl.Judge(number, req.body, &json_result);
        resp.set_content(json_result, "text/html;charset=utf-8");
    });

    svr.set_base_dir("./wwwroot");

    svr.listen("0.0.0.0", 8080);
    return 0;
}